package com.yc.xunlei;

import com.yc.url.Test2_url_urlconnection_httpurlconnection;
import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zwei
 * @create 2024-07-20 16:54
 */
public class DownLoadTask implements Runnable {
    private static Logger logger = Logger.getLogger(Test2_url_urlconnection_httpurlconnection.class);
    private int i;
    private long filesize;
    private int threads;
    private long sizePerThread;
    private String url;
    private String downloadPath;
    private DownLoadedSizeNotify dlsn;

    public DownLoadTask(int i, long filesize, int threads, long sizePerThread, String url, String downloadPath, DownLoadedSizeNotify dlsn) {
        this.i = i;
        this.filesize = filesize;
        this.threads = threads;
        this.sizePerThread = sizePerThread;
        this.url = url;
        this.downloadPath = downloadPath;
        this.dlsn = dlsn;
    }

    @Override
    public void run() {
        //计算线程要下载的起始和终止位置
        long start = i * sizePerThread;
        long end = start + sizePerThread - 1;//最后一个线程要下载的终止位置
        RandomAccessFile raf = null;
        BufferedInputStream bis = null;
        try {
            raf = new RandomAccessFile(downloadPath, "rw");
            raf.seek(start);
            //3.开始下载
            URL u = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
            //设置请求头
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Range", "bytes=" + start + "-" + end);
            connection.setConnectTimeout(3000);
            connection.connect();
            bis = new BufferedInputStream(connection.getInputStream());
            byte[] buffer = new byte[10 * 1024];
            int len = -1;
            while (  (len=bis.read(buffer,0,buffer.length))!=-1){
                raf.write(buffer,0,len);
//                logger.info("线程："+Thread.currentThread().getName()+"下载了"+len+"字节");
                if (dlsn!=null){
                    dlsn.notifySize(len);
                }
            }
//            logger.info("线程"+Thread.currentThread().getName()+"下载完毕");
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            if (bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
